package com.roncoo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

import com.roncoo.dao.UserMapper;
import com.roncoo.entity.ReturnData;
import com.roncoo.entity.User;
import com.roncoo.service.UserService;
import com.roncoo.util.JwtUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wdf
 * @since 2021-03-31
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {


    @Value("${my.jwt.effective-time}")
    private Long effectivetime;

    @Resource
    private ObjectMapper objectMapper;

    /**
     * 添加用户
     * @param user
     * @return
     */
    @Override
    public int addData(User user) {
        //判断用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uphone",user.getUphone());
        User one = this.getOne(queryWrapper);
        if (one==null){
            //不存在
            //用户默认头像
            user.setUserCreate(LocalDateTime.now());
            user.setUimage("https://jiangl.oss-cn-shanghai.aliyuncs.com/e6b0eb42-2f99-4697-84f0-e8317dd7cdb6.png");
            boolean save = this.save(user);
            return 0;
        }else {
            //已存在
            return 1;
        }
    }

    /**
     * 验证登录
     * @param user
     * @return
     */
    @Override
    public ReturnData findUser(User user) throws Exception {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uphone",user.getUphone());
        queryWrapper.eq("upassword",user.getUpassword());
        User one = this.getOne(queryWrapper);

        if (one==null){
            //不存在
            return new ReturnData(401,"账号或密码错误！！！",null,null,null,null);
        }else {
            //用户已经存在 判断用户状态
            if (one.getStatus()==1){
               //当前用户已被禁用
               return new ReturnData(666,"当前用户已被禁用，请联系管理员！！",null,null,null,null);
            }else {
                //用户能够正常登录
                String jwt = JwtUtil.createJWT("ysq", "ysq", objectMapper.writeValueAsString(user), effectivetime);
                ReturnData returnData = new ReturnData(200,"登录成功啦！！！",jwt,one.getUid(),one.getIsSvip(),one.getUserType());
                return returnData;
            }


        }
    }
}
